local skin_files = { }

minetest.register_privilege("changeskin", "Jogador pode mudar sua propria skin.")

	
lunoskins.register_skin = function(newskin)
	if newskin~=nil and newskin~="" and not minetest.registered_items["lunoskins:skin_"..newskin] then
		minetest.register_craftitem("lunoskins:skin_"..newskin, {
			description = "Skin "..newskin,
			inventory_image = "ico_skin.png",
			--inventory_image = minetest.inventorycube("face_minetest.png"),
			stack_max=1, --Acumula 6 por slot
			groups = { mobs=2 },
			on_use = function(itemstack, user, pointed_thing)
				if itemstack~=nil and user~=nil and user:is_player() then --tava dando erro desconhecido de itemstack em uma linha nao anunciada. por isso tive q por essa protecao. =S
					local oldskin = lunomods.getCharValue(user:get_player_name(), "skinname")
					if (newskin=="default" or newskin=="padrao" or not minetest.registered_items["lunoskins:skin_"..newskin]) and oldskin~=nil and minetest.registered_items["lunoskins:skin_"..oldskin] then
						lunomods.setCharValue(user:get_player_name(), "skinname", nil)
						user:get_inventory():add_item("main", ItemStack("lunoskins:skin_"..oldskin))
						lunoskins.doUpdateSkin(user)
						print("lunoskins.oldskin = '"..oldskin.."'")
						print("lunoskins.newskin = 'default'")
					elseif (newskin=="default" or newskin=="padrao" or not minetest.registered_items["lunoskins:skin_"..newskin]) and (oldskin==nil or not minetest.registered_items["lunoskins:skin_"..oldskin]) then
						lunomods.setCharValue(user:get_player_name(), "skinname", nil)
						lunoskins.doUpdateSkin(user)
						minetest.chat_send_player(user:get_player_name(), "Esta Skin nao existe ou seu personagem ja esta com a skin padrao.")
						print("lunoskins.oldskin = 'default'")
						print("lunoskins.newskin = 'default'")
					elseif minetest.registered_items["lunoskins:skin_"..newskin] and oldskin~=nil and minetest.registered_items["lunoskins:skin_"..oldskin] then
						user:get_inventory():add_item("main", ItemStack("lunoskins:skin_"..oldskin))
						lunomods.setCharValue(user:get_player_name(), "skinname", newskin)
						lunoskins.doUpdateSkin(user)
						print("lunoskins.newskin = '"..newskin.."'")
						print("lunoskins.oldskin = '"..oldskin.."'")
					elseif minetest.registered_items["lunoskins:skin_"..newskin] and (oldskin==nil or not minetest.registered_items["lunoskins:skin_"..oldskin]) then
						user:get_inventory():add_item("main", ItemStack("lunoskins:skin_padrao"))
						lunomods.setCharValue(user:get_player_name(), "skinname", newskin)
						lunoskins.doUpdateSkin(user)
						print("lunoskins.newskin = '"..newskin.."'")
						print("lunoskins.oldskin = 'default'")
					end
					minetest.sound_play("disguise", {pos=user.pos, max_hear_distance = 7}) --toca som "disguise".ogg a distancia de 7 blocos do usuario.
					itemstack:take_item()
					return itemstack
				end
			end,
		})
		
		minetest.register_alias("skin_"..newskin, "lunoskins:skin_"..newskin)
	end
end

lunoskins.listSkinMod = function(pasta)
	skin_files = lunomods.readdir(pasta, "*.png", "mobs_humanoid_")
	--print("#skin_files("..pasta..") = "..#skin_files)
	if #skin_files >=1 then
		for i, newskin in ipairs(skin_files) do 
			newskin = string.gsub(newskin, "mobs_humanoid_", "")
			newskin = string.gsub(newskin, ".png", "")
			--print("################################"..i.." --> "..newskin)
			lunoskins.register_skin(newskin)
		end
	end
end

lunoskins.register_skin("padrao")
lunoskins.listSkinMod(minetest.get_modpath("lunoskins").."/models/")
lunoskins.listSkinMod(minetest.get_modpath("lunomobs").."/models/")

--###############################################################################################

lunoskins.showSkinMod = function(name, pasta)
	skin_files = lunomods.readdir(pasta, "*.png", "mobs_humanoid_")
	minetest.chat_send_player(name, "", false)
	minetest.chat_send_player(name, "########## Listando skins ("..pasta..")... ##########", false)
	if #skin_files >=1 then
		for i, newskin in ipairs(skin_files) do 
			newskin = string.gsub(newskin, "mobs_humanoid_", "")
			newskin = string.gsub(newskin, ".png", "")
			minetest.chat_send_player(name, i.." --> "..newskin, false)
		end
	end
end

minetest.register_chatcommand("skins", {
	params = "",
	description = "Exibe todas as skins disponiveis",
	privs = {changeskin=true},
	func = function(name, param)
		lunoskins.showSkinMod(name, minetest.get_modpath("lunoskins").."/models/")
		lunoskins.showSkinMod(name, minetest.get_modpath("lunomobs").."/models/")
		minetest.chat_send_player(name, "########## (precione F10 e use a rolagem do mouse para ler nomes de skins!!!) ##########", false)
		return true
	end,
})

minetest.register_chatcommand("myskin", {
	params = "<SkinName>",
	description = "poe uma skin para se mesmo.",
	privs = {changeskin=true},
	func = function(name, param)
		local user = minetest.get_player_by_name(name)
		lunomods.setCharValue(name, "skinname", param)
		lunoskins.doUpdateSkin(user)
		return true
	end,
})

--###############################################################################################

lunoskins.setSkinHumanoid = function(player, skinname)
	if player~=nil and player:is_player() then --Caso de erro!!!
		local url = minetest.get_modpath("lunoskins").."/models/mobs_humanoid_"..tostring(skinname)..".png"
		local handler = io.open(url, 'r')
		local url2 = minetest.get_modpath("lunomobs").."/models/mobs_humanoid_"..tostring(skinname)..".png"
		local handler2 = io.open(url2, 'r')
		if handler~=nil or handler2~=nil then
			player:set_properties({
				visual = "mesh",
				textures = {"mobs_humanoid_"..skinname..".png"},
				visual_size = {x=1, y=1},
			})
			--minetest.chat_send_player(player:get_player_name(), player:get_player_name()..".skin = '"..skinname.."'.")
			minetest.log("action",player:get_player_name().." vestiu a skin '"..skinname.."'.")
			minetest.chat_send_player(player:get_player_name(), "Voce esta vestindo a skin '"..tostring(skinname).."'.")
			minetest.sound_play("disguise", {pos=player:getpos(), max_hear_distance = 7}) --toca som "disguise".ogg a distancia de 7 blocos do usuario.
		else
			minetest.chat_send_player(player:get_player_name(), "[lunoskins.setSkinHumanoid] A skin '"..tostring(skinname).."' nao existe!")
		end
	else
		--print("[lunoskins.setSkinHumanoid] ERRO CRITICO: O valor de parametro 'player' nao ser do tipo apropriado!")
		minetest.log("erro","[lunoskins.setSkinHumanoid] ERRO CRITICO: O valor de parametro 'player' nao ser do tipo apropriado!")
	end
end

lunoskins.getSkinDefault = function()
	return "padrao_sam"
end

lunoskins.doSkinDefault = function(player)
	lunoskins.setSkinHumanoid(player, lunoskins.getSkinDefault)
end


--[[
lunoskins.setSkinTeste = function(player)
	player:set_properties({
		visual = "mesh",
		mesh = "mobs_oerkki.x",
		textures = {"mobs_oerkki.png"},
		collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4},
		visual_size = {x=5, y=5},
		animation = {
			stand_start = 0,
			stand_end = 23,
			walk_start = 24,
			walk_end = 36,
			run_start = 37,
			run_end = 49,
			punch_start = 37,
			punch_end = 49,
			speed_normal = 15,
			speed_run = 15,
		},
	})
end
]]--

lunoskins.doUpdateSkin = function(player)
	local skinname = lunomods.getCharValue(player:get_player_name(), "skinname")
	if skinname~=nil and skinname~="" then
		lunoskins.setSkinHumanoid(player, skinname)
	--elseif minetest.get_player_privs(player:get_player_name())["server"] then
	--	lunoskins.setSkinHumanoid(player, "trader")
	else
		lunoskins.doSkinDefault(player)
	end
end

minetest.register_on_joinplayer(function(player)
	lunoskins.doUpdateSkin(player)
end)

minetest.register_chatcommand("setskin", {
	params = "<skin> [<Jogador>]",
	description = "Define skin de um jogador.",
	privs = {server=true},
	func = function(name, param)
	
		--local new_ownername, sx, sy, sz, ex, ey, ez = string.match(param, "(.-) (.-)")
		local skinname, name_alvo = string.match(param, "([%a%d_]+) (.+)")
		local alvo = nil
		if name_alvo~=nil and name_alvo~="" then
			alvo = minetest.get_player_by_name(name_alvo)
		else
			alvo = minetest.get_player_by_name(name)
		end
		if alvo~=nil and alvo:is_player() then
			if skinname~=nil and skinname=="default" then
				--/setskin default Stately
				lunomods.setCharValue(alvo:get_player_name(), "skinname", nil)
				--lunoskins.doSkinDefault(alvo)
				lunoskins.doUpdateSkin(alvo)
			elseif skinname~=nil and skinname~="" then
				lunomods.setCharValue(alvo:get_player_name(), "skinname", skinname)
				--lunoskins.setSkinHumanoid(alvo, skinname)
				lunoskins.doUpdateSkin(alvo)
			else
				minetest.chat_send_player(name, "[ERRO] SINTAXE: /setskin <skinname> [<Jogador>]")
				
				--lunoskins.doListSkins()
				--lunoskins.print_table2lines(lunomods.readdir(minetest.get_modpath("lunoskins").."/models/", "*.png", "mobs_humanoid_"))
				--lunoskins.print_table2lines(lunomods.readdir(minetest.get_modpath("lunomobs").."/models/", "*.png", "mobs_humanoid_"))
			end
		else
			minetest.chat_send_player(name, "[ERRO] Jogador '"..name_alvo.."' nao encontrado!")
		end
		return true -- Handled chat message
	end,
})

--[[

lunoskins.print_skins = function(table)
	print("########################################################################")
	for i, l in ipairs(table) do 
		l = string.gsub(l, "mobs_humanoid_", "")
		l = string.gsub(l, ".png", "")
		print(i.." --> "..l)
	end
	print("########################################################################")
end



lunoskins.doListSkins = function()
	local arqs = { }
	
	arqs = lunomods.readdir(minetest.get_modpath("lunoskins").."/models/", "*.png", "mobs_humanoid_")
	print("########################################################################")
	print("LISTANDO SKINS")
	print("########## lunoskins ###################################################")
	for i, l in ipairs(arqs) do 
		l = string.gsub(l, "mobs_humanoid_", "")
		l = string.gsub(l, ".png", "")
		print(i.." --> "..l)
	end
	
	arqs = lunomods.readdir(minetest.get_modpath("lunomobs").."/models/", "*.png", "mobs_humanoid_")
	print("########## lunomobs ####################################################")
	for i, l in ipairs(arqs) do 
		l = string.gsub(l, "mobs_humanoid_", "")
		l = string.gsub(l, ".png", "")
		print(i.." --> "..l)
	end
	print("########################################################################")
end

]]--
